/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package view;

import control.ShopFacade;
import javafx.collections.ObservableList;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import jpamodel.Seller;

/**
 *
 * @author Hans
 */
public class NewSellerView extends GridPane {

    private Text seller;
    private TextField sellerName, money, phone;
    private Button addSeller;
    private ShopFacade shop;
    private ObservableList<Seller> sellerList;// = FXCollections.observableArrayList(sellers);

    public NewSellerView(ObservableList<Seller> sellers, ShopFacade shop) {
        this.sellerList = sellers;
        this.shop = shop;
        setPadding(MainView.INSETS);
        setHgap(10);
        setVgap(10);
        seller = new Text("* Ny Sælger *");
        seller.setFont(MainView.getFont());
        sellerName = new TextField();
        money = new IntegerTextField();
        phone = new TextField();
        setupButtons();
        this.addRow(0, seller);
        this.addRow(1, new Label("Sælger"), new Label("Telefon"), new Label("Tilgodehavende"));
        this.addRow(2, sellerName, phone, money);
        this.addRow(3, addSeller);
    }

    private boolean validateSeller() {
        boolean result = true;
        if (sellerName.getText().trim().isEmpty()
                || money.getText().trim().isEmpty()
                || phone.getText().trim().isEmpty()) {
            TextFieldValidation.setRed(sellerName);
            TextFieldValidation.setRed(money);
            TextFieldValidation.setRed(phone);
            result = false;
        }
        return result;
    }

    public void update() {
        if (shop.getDBC().isConnected()) {
            sellerList.removeAll(shop.getAllSellers());
            sellerList.clear();
            sellerList.addAll(shop.getAllSellers());
        }
    }
    
    private void setupButtons() {
        addSeller = new Button("Tilføj ny Sælger");
        addSeller.getStyleClass().add("mybutton");
        addSeller.setOnAction(event -> {
            if (validateSeller()) {
                Seller newSeller = new Seller();
                newSeller.setName(sellerName.getText());
                newSeller.setMoney(Integer.parseInt(money.getText()));
                newSeller.setPhone(phone.getText());
                shop.persist(newSeller);
            }
        });
    }

}
